﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;

namespace NCache.Controllers
{
    [Route("api/[controller]/[action]")]
    public class ValuesController : Controller
    {
        private readonly IDistributedCache _distributedCache;
        private readonly ILogger<ValuesController> _logger;
        public ValuesController(IDistributedCache distributedCache,
            ILogger<ValuesController> logger)
        {
            _distributedCache = distributedCache;
            _logger = logger;
        }
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public async Task<string> GetAsync(int id)
        {
            var val = await _distributedCache.GetStringAsync("value1");
            _logger.LogInformation($"从缓存中取键为value1的值为{val}");
            if (val == null)
            {
                await _distributedCache.SetStringAsync("value1", "value2");
                _logger.LogInformation($"向缓存中存储value1:{val}");
            }
            val = await _distributedCache.GetStringAsync("value1");
            _logger.LogInformation($"从缓存中取键为value1的值为{val}");
            return val;
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
